import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/UI/AudioPlayerPage.dart';
import 'package:hitutor/UI/VideoPlayerPage.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'MyButton.dart';
import 'MyDialog.dart';
import 'MyImage.dart';

class AudioPlayBar extends StatefulWidget {
  List<dynamic> audioFiles = [];
  List<dynamic> videoFiles = [];
  int mode;

  AudioPlayBar({required this.mode, required this.audioFiles, required this.videoFiles});

  @override
  State<StatefulWidget> createState() {
    return _AudioPlayBar();
  }
}

class _AudioPlayBar extends State<AudioPlayBar> {
  AudioPlayer audioPlayer = AudioPlayer();
  PlayerState playerState = PlayerState.STOPPED;
  int maxMS = 0;
  int playMS = 0;

  int playPos = 0;

  late String type;
  late String url;
  late String name;

  @override
  void initState() {
    if (widget.mode == AudioPlayerPage.materialMode) {
      type = "materialFileType";
      url = "materialFileUrl";
      name = "materialFileName";
    } else {
      type = "fileType";
      url = "url";
      name = "fileName";
    }

    audioPlayer.onAudioPositionChanged.listen((p) {
      playMS = p.inMilliseconds;
      setState(() {});
    });
    audioPlayer.onDurationChanged.listen((Duration d) {
      maxMS = d.inMilliseconds;
      print('Max duration: $maxMS');
      setState(() {});
    });
    audioPlayer.onPlayerStateChanged.listen((event) {
      print('onPlayerStateChanged: $event');
      playerState = event;
      //播放完毕自动播放下一首
      // if (playerState == PlayerState.COMPLETED) {
      //   nextClick();
      //   return;
      // }
      setState(() {});
    });
    // play();
    super.initState();
  }

  play() async {
    if (playPos >= widget.audioFiles.length) {
      return;
    }
    String _url = widget.audioFiles[playPos][url] ?? "";
    if (_url.isEmpty) {
      showToast("url為空");
      return;
    }
    int result = await audioPlayer.play(_url);
    if (result == 1) {
      print('play success');
    } else {
      print('play failed');
      showToast('play failed');
    }
  }

  pause() async {
    int result = await audioPlayer.pause();
    if (result == 1) {
      print('pause success');
    } else {
      print('pause failed');
      showToast('pause failed');
    }
  }

  resume() async {
    int result = await audioPlayer.resume();
    if (result == 1) {
      // success
      print('resume success');
    } else {
      print('resume failed');
      showToast('resume failed');
    }
  }

  seek(int startMilliseconds) async {
    int result = await audioPlayer.seek(Duration(milliseconds: startMilliseconds));
    if (result == 1) {
      print('go to success');
      // await audioPlayer.resume();
    } else {
      showToast("go to failed");
      print('go to failed');
    }
  }

  @override
  void deactivate() async {
    int result = await audioPlayer.release();
    if (result == 1) {
      print('release success');
    } else {
      showToast('release failed');
    }
    super.deactivate();
  }

  playOrPause() {
    if (playerState == PlayerState.PLAYING) {
      pause();
    } else if (playerState == PlayerState.PAUSED) {
      resume();
    } else {
      audioPlayer.stop();
      play();
    }
  }

  lastClick() {
    audioPlayer.stop();
    playPos = playPos == 0 ? (widget.audioFiles.length - 1) : (playPos - 1);
    play();
    setState(() {});
  }

  nextClick() {
    audioPlayer.stop();
    playPos = playPos == (widget.audioFiles.length - 1) ? 0 : (playPos + 1);
    play();
    setState(() {});
  }

  videoMenuClick() {
    if (widget.videoFiles.length < 1) {
      showToast("暫無視頻文檔");
      return;
    }
    List<String> videoNames = [];
    for (var item in widget.videoFiles) {
      videoNames.add(item[name]);
    }
    showBottomDialog(
        context,
        MenuView(videoNames, (i) {
          if (playerState == PlayerState.PLAYING) {
            pause();
          }
          String videoUrl = widget.videoFiles[i][url] ?? "";
          if (videoUrl.isEmpty) {
            showToast("url為空");
            return;
          }
          PageUtil().open(context, VideoPlayerPage(videoUrl));
        }));
  }

  audioMenuClick() {
    if (widget.audioFiles.length < 1) {
      showToast("暫無音頻文檔");
      return;
    }
    List<String> audioNames = [];
    for (var item in widget.audioFiles) {
      audioNames.add(item[name]);
    }
    showBottomDialog(
        context,
        MenuView(audioNames, (i) {
          audioPlayer.stop();
          playPos = i;
          play();
          setState(() {});
        }));
  }

  ms2time(int ms) {
    int s = (ms + 500) ~/ 1000;
    int mm = s ~/ 60;
    int ss = s % 60;
    String MM = TwoDigits(mm);
    String SS = TwoDigits(ss);
    return "$MM:$SS";
  }

  @override
  Widget build(BuildContext context) {
    double playProgress = maxMS > 0 ? (playMS / maxMS) : 0;
    String playTime = ms2time(playMS);
    String maxTime = ms2time(maxMS);
    String playAudioName = playPos >= widget.audioFiles.length ? "" : "${widget.audioFiles[playPos][name]}";
    return Column(children: [
      Slider(
          activeColor: MyColor.Green,
          value: playProgress,
          onChanged: (value) {
            int preToMS = (maxMS * value).toInt();
            seek(preToMS);
          }),
      Container(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 16),
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          Text("$playTime", style: TextStyle(fontSize: 10, color: MyColor.Green)),
          Text(playAudioName, style: TextStyle(fontSize: 15, color: MyColor.Green)),
          Text(maxTime, style: TextStyle(fontSize: 10, color: MyColor.Green)),
        ]),
      ),
      Container(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 16),
        child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          LocalImage("video_list.png", width: 32, onTap: videoMenuClick),
          LocalImage("ic_play_last.png", width: 32, onTap: lastClick),
          LocalImage(playerState == PlayerState.PLAYING ? "play_pause.png" : "play_start.png",
              width: 48, padding: EdgeInsets.all(0), onTap: playOrPause),
          LocalImage("ic_play_next.png", width: 32, onTap: nextClick),
          LocalImage("audio_list.png", width: 32, onTap: audioMenuClick),
        ]),
      )
    ]);
  }
}

class MenuView extends StatelessWidget {
  List<String> menus;
  Function(int index) onSelected;

  MenuView(this.menus, this.onSelected);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      shrinkWrap: true,
      itemCount: menus.length,
      itemBuilder: (BuildContext context, int index) {
        return TextBtn(menus[index], height: 48, width: double.infinity, style: TextStyle(fontSize: 14), onTap: () {
          PageUtil().back(context);
          onSelected(index);
        });
      },
      separatorBuilder: (BuildContext context, int index) {
        return Container(height: 0.5, color: MyColor.EE);
      },
    );
  }
}
